package com.aiyige.page.player;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.page.player.dialog.PlayListMenuView;
import com.aiyige.page.player.dialog.PlaySpeedView;
import com.aiyige.page.player.interfaces.IPlayStatus;
import com.aiyige.page.player.view.IPlayerView;
import com.aiyige.page.player.widget.PlayerSeekBar;
import com.aiyige.page.test.STBManager;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.UIHelper;
import com.pili.pldroid.player.IMediaController;
import com.pili.pldroid.player.PlayerState;

/**
 * Created by xiachao on 2017/8/11.
 */

public class PlayerController extends FrameLayout implements IMediaController, IPlayStatus, View.OnClickListener {
    private static final String TAG = "PlayerController";
    private MediaPlayerControl mPlayer;
    private Context mContext;
    //    private PopupWindow mWindow;
    private int mAnimStyle;
//    private View mAnchor;
    //    private View mRoot;
    private PlayerSeekBar mProgress;
    private TextView mEndTime, mCurrentTime;
    private long mDuration;
    private boolean mShowing;
    private boolean mDragging;
    private boolean mInstantSeeking = true;
    private static int sDefaultTimeout = 600000;
    private static final int SEEK_TO_POST_DELAY_MILLIS = 200;
    private static int SEEK_BAR_MAX_1000 = 1000;
    private static final int FADE_OUT = 1;
    private static final int SHOW_PROGRESS = 2;
    private boolean mFromXml = false;
    private ImageView mPauseButtonMini;
    private ImageView mPauseButtonBig;
    
    // 默认1.0
    private PlaySpeed playSpeed = PlaySpeed.newBuilder().name("100%").value(PlaySpeed.SPEED_PERCENT_100).build();
    private AudioManager mAM;
    private Runnable mLastSeekBarRunnable;
    //    private boolean mDisableProgress = false;
    private OnClickSpeedAdjustListener mOnClickSpeedAdjustListener;
    //    private RelativeLayout rlFull;
    private ImageView ivFull;
    private PlayerView playerView;

    private LinearLayout llBottomParent;// 底部

    private LinearLayout llSpeedMirrorRight;// 右侧的 底部AB循环 倍速 镜像

    private TextView tvABRight;

    private TextView tvSpeedRight;

    private TextView tvMirrorRight;

    private LinearLayout llSpeedMirrorBottom;

    private TextView tvABBottom;

    private TextView tvSpeedBottom;

    private TextView tvMirrorBottom;

    private ImageView ivDownload;

    private ImageView ivLock;




    private View topLayout;

    private View bottomLayout;

    private boolean mirror = false;



    private boolean isLock = false;

    private boolean isAbShow = false;

    View rootView;

    View backView;

    TextView tvTitle;

    ImageView ivMenu;

    View topView;

//    DialogPlayList dialogPlayList;

//    DialogPlaySpeed dialogPlaySpeed;

    PlaySpeedView playSpeedView;

    PlayListMenuView playListMenuView;

    private boolean isLandscape;

    public IPlayerView getiPlayerView() {
        return iPlayerView;
    }

    public void setiPlayerView(IPlayerView iPlayerView) {
        this.iPlayerView = iPlayerView;
    }

    private IPlayerView iPlayerView;

//    private boolean isV04 = false;

    public interface OnClickSpeedAdjustListener {
        void onClickNormal();

        void onClickFaster();

        void onClickSlower();
    }

    public PlayerController(Context context, AttributeSet attrs) {
        super(context, attrs);
        mFromXml = true;
        initController(context);
    }

    public PlayerController(Context context) {
        super(context);
        if (!mFromXml && initController(context))
            initFloatingWindow();
    }

    public PlayerController(Context context, PlayerView playerView, boolean useFastForward, boolean disableProgressBar) {
        this(context);
        this.playerView = playerView;
//        initControllerView();

    }

    public PlayerController(Context context, boolean useFastForward) {
        this(context);
    }

    public void refreshProgress() {
        setProgress();
    }

    public void setOnClickSpeedAdjustListener(OnClickSpeedAdjustListener listener) {
        mOnClickSpeedAdjustListener = listener;
    }

    private boolean initController(Context context) {
        mContext = context;
        mAM = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        initControllerView();
        return true;
    }

    @Override
    public void onFinishInflate() {
        initControllerView();
        super.onFinishInflate();
    }

    private void initFloatingWindow() {
//        mWindow = new PopupWindow(mContext);
//        mWindow.setFocusable(false);
//        mWindow.setBackgroundDrawable(null);
//        mWindow.setOutsideTouchable(true);
        mAnimStyle = android.R.style.Animation;
    }


    private void initControllerView() {
        if (rootView == null) {
            rootView = FrameLayout.inflate(mContext, R.layout.player_control, this);
        } else {
            return;
        }
        mPauseButtonMini = (ImageView) rootView.findViewById(R.id.iv_play_pause_mini);
        mPauseButtonBig = (ImageView) rootView.findViewById(R.id.iv_play_pause_big);
        if (mPauseButtonMini != null) {
            mPauseButtonMini.requestFocus();
            mPauseButtonMini.setOnClickListener(mPauseListener);
        }
        if (mPauseButtonBig != null) {
            mPauseButtonBig.requestFocus();
            mPauseButtonBig.setOnClickListener(mPauseListener);
        }

        mProgress = (PlayerSeekBar) rootView.findViewById(R.id.seek_bar_player);

        if (mProgress != null) {
//            if (mProgress instanceof SeekBar) {
//                SeekBar seeker = (SeekBar) mProgress;
//                seeker.setOnSeekBarChangeListener(mSeekListener);
////                seeker.setThumbOffset(1);
//            }
            mProgress.setListener(seekBarListener);

//            mProgress.setEnabled(!mDisableProgress);
        }

        mEndTime = (TextView) rootView.findViewById(R.id.tv_end);
        mCurrentTime = (TextView) rootView.findViewById(R.id.tv_start);
        ivFull = (ImageView) rootView.findViewById(R.id.iv_full_screen);
        ivFull.setOnClickListener(this);

        llSpeedMirrorRight = (LinearLayout) rootView.findViewById(R.id.ll_speed_mirror_right);
        llBottomParent= (LinearLayout) rootView.findViewById(R.id.ll_bottom_parent);
        llSpeedMirrorBottom = (LinearLayout) rootView.findViewById(R.id.ll_speed_mirror_bottom);
        topLayout = rootView.findViewById(R.id.rl_player_top);
        bottomLayout = rootView.findViewById(R.id.rl_player_control);


        tvSpeedRight = (TextView) rootView.findViewById(R.id.tv_speed_right);
        tvMirrorRight = (TextView) rootView.findViewById(R.id.tv_mirror_right);
        tvABRight = (TextView) rootView.findViewById(R.id.tv_ab_right);

        tvSpeedBottom = (TextView) rootView.findViewById(R.id.tv_speed_bottom);
        tvMirrorBottom = (TextView) rootView.findViewById(R.id.tv_mirror_bottom);
        tvABBottom = (TextView) rootView.findViewById(R.id.tv_ab_bottom);


        backView = rootView.findViewById(R.id.iv_back);
        tvTitle = (TextView) rootView.findViewById(R.id.tv_title);
        ivMenu = (ImageView) rootView.findViewById(R.id.top_choice);
        topView = rootView.findViewById(R.id.rl_player_top);
        ivDownload = (ImageView) rootView.findViewById(R.id.top_download);
        ivLock = (ImageView) rootView.findViewById(R.id.iv_lock);
        backView.setOnClickListener(this);
        ivMenu.setOnClickListener(this);
        tvSpeedRight.setOnClickListener(this);
        tvMirrorRight.setOnClickListener(this);
        tvABRight.setOnClickListener(this);
        tvSpeedBottom.setOnClickListener(this);
        tvMirrorBottom.setOnClickListener(this);
        tvABBottom.setOnClickListener(this);
        ivDownload.setOnClickListener(this);
        ivLock.setOnClickListener(this);
    }

    /**
     * Control the action when the seekbar dragged by user
     *
     * @param seekWhenDragging True the media will seek periodically
     */
    public void setInstantSeeking(boolean seekWhenDragging) {
        mInstantSeeking = seekWhenDragging;
    }

    private void disableUnsupportedButtons() {
        try {
            if (mPauseButtonMini != null && !mPlayer.canPause()) {
                mPauseButtonMini.setEnabled(false);
            }
            if (mPauseButtonBig != null && !mPlayer.canPause()) {
                mPauseButtonBig.setEnabled(false);
            }
        } catch (Exception ex) {
        }
    }

    /**
     * <p>
     * Change the animation style resource for this controller.
     * </p>
     * <p>
     * <p>
     * If the controller is showing, calling this method will take effect only
     * the next time the controller is shown.
     * </p>
     *
     * @param animationStyle animation style to use when the controller appears and disappears.
     *                       Set to -1 for the default animation, 0 for no animation,
     *                       or a resource identifier for an explicit animation.
     */
    public void setAnimationStyle(int animationStyle) {
        mAnimStyle = animationStyle;
    }


    public interface OnShownListener {
        public void onShown();
    }

    private OnShownListener mShownListener;

    public void setOnShownListener(OnShownListener l) {
        mShownListener = l;
    }

    public interface OnHiddenListener {
        public void onHidden();
    }

    private OnHiddenListener mHiddenListener;

    public void setOnHiddenListener(OnHiddenListener l) {
        mHiddenListener = l;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            long pos;
            switch (msg.what) {
                case FADE_OUT:
                    hideWidget();
                    break;
                case SHOW_PROGRESS://播放器此时可能还在初始化，等待初始化成功mPlayer不为null再来刷新
                    if (mPlayer == null || !mPlayer.isPlaying()) {
                        msg = obtainMessage(SHOW_PROGRESS);
                        sendMessageDelayed(msg, SEEK_BAR_MAX_1000 - (0 % SEEK_BAR_MAX_1000));
                        return;
                    }
                    Log.i("","refreshPlayer-setProgress（）");
                    pos = setProgress();
                    if (pos == -1) {
                        return;
                    }
                    if (!mDragging && mShowing) {
                        msg = obtainMessage(SHOW_PROGRESS);
                        sendMessageDelayed(msg, SEEK_BAR_MAX_1000 - (pos % SEEK_BAR_MAX_1000));
                        updatePausePlay();
                    }
                    break;
            }
        }
    };


    public void setProgress(int progress) {
        if (mProgress != null) {
            mProgress.setMediaDurationMs(progress);
        }
    }

    private long setProgress() {
        if (mPlayer == null || mDragging) {
            Log.i("","refreshPlayer-pos mPlayer == null || mDragging");
            return 0;
        }
        if (mProgress == null) {
            return 0;
        }
        long position = mPlayer.getCurrentPosition();
        long duration = mPlayer.getDuration();
        mProgress.setMediaDurationMs(duration);
        if (mProgress != null) {
            if (duration > 0) {
                long pos = 1000L * position / duration;
                mProgress.updateProgressMs((int) pos);
            }
            int percent = mPlayer.getBufferPercentage();
            mProgress.setSecondaryProgress(percent * 10);
        }

        mDuration = duration;

        if (mEndTime != null){
            mEndTime.setText(generateTime(mDuration));
        }
        if (mCurrentTime != null){
            mCurrentTime.setText(generateTime(position));
            Log.i("playerIndex","refreshPlayer mCurrentTime:"+generateTime(mDuration)+" "+generateTime(position));
        }


        return position;
    }

    private static String generateTime(long position) {
//        int totalSeconds = (int) (position / SEEK_BAR_MAX_1000);
//
//        int seconds = totalSeconds % 60;
//        int minutes = (totalSeconds / 60) % 60;
//        int hours = totalSeconds / 3600;
//
//        if (hours > 0) {
//            return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes,
//                    seconds).toString();
//        } else {
//            return String.format(Locale.US, "%02d:%02d", minutes, seconds)
//                    .toString();
//        }
        return TimeUtils.getDurationTime(position);
    }
//
//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        show(sDefaultTimeout);
//        return true;
//    }
//
//    @Override
//    public boolean onTrackballEvent(MotionEvent ev) {
//        show(sDefaultTimeout);
//        return false;
//    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mPlayer == null) {
            return super.dispatchKeyEvent(event);
        }
        int keyCode = event.getKeyCode();
        if (event.getRepeatCount() == 0
                && (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
                || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_SPACE)) {
            doPauseResume();
            show(sDefaultTimeout);
            if (mPauseButtonMini != null)
                mPauseButtonMini.requestFocus();
            if (mPauseButtonBig != null)
                mPauseButtonBig.requestFocus();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
                updatePausePlay();
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK
                || keyCode == KeyEvent.KEYCODE_MENU) {
            hideWidget();
            return true;
        } else {
            show(sDefaultTimeout);
        }
        return super.dispatchKeyEvent(event);
    }

    private View.OnClickListener mPauseListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (mOnClickSpeedAdjustListener != null) {
                mOnClickSpeedAdjustListener.onClickNormal();
            }
            doPauseResume();
            show(sDefaultTimeout);
        }
    };

    public void updatePausePlay() {
        if (mPauseButtonMini == null || mPlayer == null || mPauseButtonBig ==null)
            return;
        if (mPlayer.isPlaying()) {
            mPauseButtonMini.setImageResource(R.drawable.detail_pause);
            mPauseButtonBig.setImageResource(R.drawable.player_pause);
        } else {
            mPauseButtonMini.setImageResource(R.drawable.detail_play);
            mPauseButtonBig.setImageResource(R.drawable.player_play);
        }
    }

    private void doPauseResume() {
        if (mPlayer == null) {
            return;
        }
        if (mPlayer.isPlaying())
            mPlayer.pause();
        else
            mPlayer.start();
        updatePausePlay();
        STBManager.getInstance().doPresenterPause();
    }

    public PlayerSeekBar.PlayerSeekBarListener seekBarListener = new PlayerSeekBar.PlayerSeekBarListener() {
        @Override
        public void onStartTrackingTouch(SeekBar bar) {
            if (mPlayer == null) {
                return;
            }
            Log.i("testPlayer","onStartTrackingTouch");
            mDragging = true;
            show(3600000);
            mHandler.removeMessages(SHOW_PROGRESS);
            if (mInstantSeeking)
                mAM.setStreamMute(AudioManager.STREAM_MUSIC, true);
        }

        @Override
        public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
            if (mPlayer == null) {
                return;
            }
            if (!fromuser) {
                return;
            }
            final long newposition = (long) (mDuration * progress) / SEEK_BAR_MAX_1000;
            String time = generateTime(newposition);
//            if (mInstantSeeking) {
//                mHandler.removeCallbacks(mLastSeekBarRunnable);
////                mLastSeekBarRunnable = new Runnable() {
////                    @Override
////                    public void run() {
////
//////                        playerView.seekTo(newposition);
////                        mPlayer.seekTo(newposition);
////                    }
////                };
//                mHandler.postDelayed(mLastSeekBarRunnable, SEEK_TO_POST_DELAY_MILLIS);
//            }
            if (mCurrentTime != null)
                mCurrentTime.setText(time);

            Log.i("testPlayer","onProgressChanged");
        }

        @Override
        public void onStopTrackingTouch(SeekBar bar) {
            if (mPlayer == null) {
                return;
            }
//            mLastSeekBarRunnable = new Runnable() {
//                @Override
//                public void run() {
//
////                        playerView.seekTo(newposition);
//                    mPlayer.seekTo(newposition);
//                }
//            };
            mPlayer.seekTo(mDuration * bar.getProgress() / 1000);
            if (playerView != null) {
                playerView.setPresenterChanged(true);
            }
            Log.i("testPlayer","onStopTrackingTouch");
//            if (!mInstantSeeking)
//                mPlayer.seekTo(mDuration * bar.getProgress() / 1000);

            show(sDefaultTimeout);
            mHandler.removeMessages(SHOW_PROGRESS);
            mAM.setStreamMute(AudioManager.STREAM_MUSIC, false);
            mDragging = false;
            mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
        }

        @Override
        public void onSeek(long position) {
            if (mPlayer == null) {
                return;
            }
            Log.i("testPlayer","onSeek");
//            mPlayer.seekTo(position);
        }
    };


    /**
     * Set the view that acts as the anchor for the control view.
     * <p>
     * - This can for example be a VideoView, or your Activity's main view.
     * - AudioPlayer has no anchor view, so the view parameter will be null.
     *
     * @param view The view to which to anchor the controller when it is visible.
     */
    @Override
    public void setAnchorView(View view) {
//        mAnchor = view;
//        if (mAnchor == null) {
////            sDefaultTimeout = 0; // show forever
//        }
//        if (!mFromXml) {
//            removeAllViews();
//            mRoot = makeControllerView();
//            mWindow.setContentView(mRoot);
//            mWindow.setWidth(LayoutParams.MATCH_PARENT);
//            mWindow.setHeight(LayoutParams.WRAP_CONTENT);
//        }
//        initControllerView();
    }

    @Override
    public void setMediaPlayer(MediaPlayerControl player) {
        mPlayer = player;
        updatePausePlay();
    }

    /**
     * 由于七牛内部控制器根据onTouch调用了show和hide
     * 我们需要改成单击，所以这个方法废弃掉
     */
    @Deprecated
    @Override
    public void show() {
    }

    public void showWidget() {
        Log.i("","refreshPlayer-showWidget");
        show(sDefaultTimeout);
    }

    public void onSingleTap() {
        dissMissDialog();
    }

    /**
     * 判断是否有弹出框正在显示,如果正在显示,则消失,不把单击事件传递给其他控件
     * @return
     */
    public boolean isDialogShowing() {
        boolean isShowing = false;
        if (playListMenuView != null && playListMenuView.isShown()) {
            isShowing = true;
        }
        if (playSpeedView != null && playSpeedView.isShown()) {
            isShowing = true;
        }
        return isShowing;
    }

    /**
     * Show the controller on screen. It will go away automatically after
     * 'timeout' milliseconds of inactivity.
     *
     * @param timeout The timeout in milliseconds. Use 0 to show the controller until hide() is called.
     */
    @Override
    public void show(int timeout) {
        if (isLock()) {
            ivLock.setVisibility(View.VISIBLE);
            hideLockDelayed();
            return;
        }
        if (playerView != null && playerView.getPlayerState() == PlayerState.COMPLETED) {
            setProgress();
        }
        if (!mShowing) {
//            if (mAnchor != null && mAnchor.getWindowToken() != null) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//                    mAnchor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//                }
//            }
            if (mPauseButtonMini != null) {
                mPauseButtonMini.requestFocus();
            }
            if (mPauseButtonBig != null) {
                mPauseButtonBig.requestFocus();
            }
            disableUnsupportedButtons();
            setVisibility(View.VISIBLE);
//            if (mFromXml) {
//                setVisibility(View.VISIBLE);
//            } else {
//                int[] location = new int[2];
//
//                if (mAnchor != null) {
//                    mAnchor.getLocationOnScreen(location);
//                    Rect anchorRect = new Rect(location[0], location[1],
//                            location[0] + mAnchor.getWidth(), location[1]
//                            + mAnchor.getHeight());
//
////                    mWindow.setAnimationStyle(mAnimStyle);
////                    mWindow.showAtLocation(mAnchor, Gravity.BOTTOM,
////                            anchorRect.left, 0);
//                    setVisibility(View.VISIBLE);
//                } else {
//                    Rect anchorRect = new Rect(location[0], location[1],
//                            location[0] + this.getWidth(), location[1]
//                            + this.getHeight());
//
////                    mWindow.setAnimationStyle(mAnimStyle);
////                    mWindow.showAtLocation(mRoot, Gravity.BOTTOM,
////                            anchorRect.left, 0);
////                    setCu
//                    setVisibility(View.VISIBLE);
//                }
//            }
            mShowing = true;
            if (mShownListener != null)
                mShownListener.onShown();
        }
        updatePausePlay();
        mHandler.removeMessages(SHOW_PROGRESS);
        mHandler.sendEmptyMessage(SHOW_PROGRESS);

        if (timeout != 0) {
            mHandler.removeMessages(FADE_OUT);
            mHandler.sendMessageDelayed(mHandler.obtainMessage(FADE_OUT),
                    timeout);
        }
    }

    @Override
    public boolean isShowing() {
        return mShowing;
    }

    /**
     * 由于七牛内部控制器根据onTouch调用了show和hide
     * 我们需要改成单击，所以这个方法废弃掉
     * 外部调用采用hideWidget()
     */
    @Deprecated
    @Override
    public void hide() {
    }

    public void hideWidget() {
        if (mShowing) {
//            if (mAnchor != null) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//                    //mAnchor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
//                }
//            }
            try {
                mHandler.removeMessages(SHOW_PROGRESS);
//                if (mFromXml)
//                    setVisibility(View.INVISIBLE);
//                else
////                    mWindow.dismiss();
//
                setVisibility(View.INVISIBLE);
            } catch (IllegalArgumentException ex) {
//                Log.d(TAG, "MediaController already removed");
            }
            mShowing = false;
            if (mHiddenListener != null)
                mHiddenListener.onHidden();

            if (isLock()) {
                ivLock.setVisibility(View.VISIBLE);
                hideLockDelayed();
            }

            if (isAbShow) {
                timingHandler.sendEmptyMessage(0);
            }
        }
    }

    @Override
    public void setVisibility(int visibility) {
        if (isLandscape) {
            mPauseButtonBig.setVisibility(visibility);
            topLayout.setVisibility(visibility);
            ivLock.setVisibility(visibility);

        } else {
            topLayout.setVisibility(View.INVISIBLE);
            ivLock.setVisibility(View.INVISIBLE);
        }

        llBottomParent.setVisibility(visibility);
    }

    private void hideLockDelayed() {
        lockHandler.removeMessages(0);
        lockHandler.sendEmptyMessageDelayed(0,sDefaultTimeout);
    }

    Handler lockHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            ivLock.setVisibility(View.INVISIBLE);
        }
    };

    @Override
    public void setEnabled(boolean enabled) {
        if (mPauseButtonMini != null) {
            mPauseButtonMini.setEnabled(enabled);
        }
        if (mPauseButtonBig != null) {
            mPauseButtonBig.setEnabled(enabled);
        }
//        if (mFfwdButton != null) {
//            mFfwdButton.setEnabled(enabled);
//        }
//        if (mRewButton != null) {
//            mRewButton.setEnabled(enabled);
//        }
        if (mProgress != null)
            mProgress.setEnabled(enabled);
        disableUnsupportedButtons();
        super.setEnabled(enabled);
    }

    public PlaySpeed getPlaySpeed() {
        return playSpeed;
    }

    private void showSpeedDialog() {
        if (playSpeedView == null) {
            playSpeedView = (PlaySpeedView)rootView.findViewById(R.id.play_speed_view);
            playSpeedView.setPlayerController(this);
        }
        playSpeedView.show();
    }


    private void setAb() {
        isAbShow = !isAbShow;
        mProgress.setShowRangeView(isAbShow);
    }

    private void setMirror() {
        mirror = !mirror;
        playerView.setMirror(mirror);
        tvMirrorRight.setTextColor(ContextCompat.getColor(mContext, mirror ? R.color.zwcolor_pink_f93684 : R.color.white));
        tvMirrorBottom.setTextColor(ContextCompat.getColor(mContext, mirror ? R.color.zwcolor_pink_f93684 : R.color.white));
    }

    public void setScreenRotate(boolean isLandscape) {
        this.isLandscape = isLandscape;
        if (isLandscape) {
            llSpeedMirrorRight.setVisibility(playerView.isVerticalVideo() ?View.GONE:View.VISIBLE);
            llSpeedMirrorBottom.setVisibility(playerView.isVerticalVideo()  ?View.VISIBLE:View.GONE);
        } else {
            llSpeedMirrorRight.setVisibility(View.GONE);
            llSpeedMirrorBottom.setVisibility(View.GONE);
        }
//        llSpeedMirrorRight.setVisibility(isLandspace  ? View.GONE : View.VISIBLE);
//        llSpeedMirrorBottom.setVisibility(isLandspace ? View.VISIBLE : View.GONE);
        ivFull.setVisibility(isLandscape ? View.GONE : View.VISIBLE);
        topView.setVisibility(isLandscape ? View.VISIBLE : View.INVISIBLE);
        mPauseButtonMini.setVisibility(isLandscape ? View.GONE : View.VISIBLE);
        mPauseButtonBig.setVisibility(isLandscape ? View.VISIBLE : View.INVISIBLE);
        mProgress.setShowRangeView(false);
        if (!isLandscape) {//由于收费视频，所以返回到mini竖屏播放器的时候，dialog需自动消失
            dissMissDialog();
            ivLock.setVisibility(View.INVISIBLE);
            setLock(false);
        } else {
            ivLock.setVisibility(View.VISIBLE);
        }

        bottomLayout.setBackground(ContextCompat.getDrawable(mContext,isLandscape?R.color.transparent:R.color.zwcolor_black_7f000000));
        RelativeLayout.LayoutParams rl = (RelativeLayout.LayoutParams)llBottomParent.getLayoutParams();
        rl.height = UIHelper.dip2px(isLandscape&&playerView.isVerticalVideo()?80:40);
        llBottomParent.setLayoutParams(rl);
    }

    private void dissMissDialog() {
        if (playListMenuView != null && playListMenuView.isShown()) {
            playListMenuView.dismiss();
        }
        if (playSpeedView != null && playSpeedView.isShown()) {
            playSpeedView.dismiss();
        }

    }

    public void setPlaySpeed(PlaySpeed playSpeed) {
        this.playSpeed = playSpeed;
        playerView.setPlaySpeed(playSpeed.getValue());
//        tvSpeedRight.setText(playSpeed.getName());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_full_screen:
                if (!playerView.buyLayoutShowing()) {
                    playerView.setFullScreen(true);
                }
                break;
            case R.id.tv_speed_right:
            case R.id.tv_speed_bottom:
                showSpeedDialog();
//                RxBarTool.FLAG_FULLSCREEN((BaseActivity)mContext);
//                UIHelper.hideSystemUI((BaseActivity)mContext);
                break;
            case R.id.tv_mirror_right:
            case R.id.tv_mirror_bottom:
                setMirror();
                break;
            case R.id.tv_ab_right:
            case R.id.tv_ab_bottom:
                setAb();
                break;
            case R.id.iv_back:
                doBack();
                break;
            case R.id.top_choice:
                showPlayListDialog();
//                RxBarTool.FLAG_FULLSCREEN((BaseActivity)mContext);
//                UIHelper.hideSystemUI((BaseActivity)mContext);
                break;
            case R.id.top_download:
                download();
                break;
            case R.id.iv_lock:
                doLock();
                break;
        }
    }

    /**
     * 最终传递到page页去实现下载逻辑
     */
    private void download() {
        if (playerView != null) {
            playerView.download();
        }
    }

    public void doLock() {
        setLock(!isLock());
        ivLock.setSelected(isLock());
        if (isLock()) {
            dissMissDialog();
            hideWidget();
        } else {
            showWidget();
        }
    }

    public void doBack() {
        if (isLock()) {
            return;
        }
        if (playerView != null) {
            playerView.doBack();
        }
    }

    public void playOrPause() {
        if (mPauseButtonMini != null && mPauseButtonMini.getVisibility() == View.VISIBLE) {
            mPauseButtonMini.performClick();
        }
        else if (mPauseButtonBig != null && mPauseButtonBig.getVisibility() == View.VISIBLE) {
            mPauseButtonBig.performClick();
        }
    }

    public void seekTo(int percent) {
        if (mPlayer != null) {
            mPlayer.seekTo(mDuration * (percent * 10) / SEEK_BAR_MAX_1000);
        }
    }

    public void seekTo(long time) {
        if (mPlayer != null) {
            mPlayer.seekTo(time);
        }
    }


    public IPlayStatus getPlayStatus() {
        return this;
    }


    private void showPlayListDialog() {
        if (playListMenuView == null) {
            playListMenuView = (PlayListMenuView) rootView.findViewById(R.id.play_list_menu_view);
            playListMenuView.setPlayerController(this);
        }
        playListMenuView.show();
    }

    /**
     * 切歌
     */
    public void onNext() {
        if (isShowing()) {
            showWidget();
        }
        if (getiPlayerView() != null) {
            tvTitle.setText(getiPlayerView().getTitle());
        }
        if (playListMenuView != null && playListMenuView.isShown()) {
            playListMenuView.setCurrentPlayInfo(getiPlayerView().getCurrentPlayInfo());
            playListMenuView.notifyDataChanged();
        }
    }

    public void onSwitch(int index) {
        playerView.setStopLoopPlayback(true);
        playerView.play(index);
    }


    public void setVisibleDownload(boolean visibleDownload) {
        if (ivDownload != null) {
            ivDownload.setVisibility(visibleDownload?View.VISIBLE:View.GONE);
        }
    }

    public void setVisibleMenu(boolean visibleMenu) {
        if (ivMenu != null && visibleMenu) {
            ivMenu.setVisibility(visibleMenu?View.VISIBLE:View.GONE);
        }
    }

    public boolean isLock() {
        return isLock;
    }

    public void setLock(boolean lock) {
        isLock = lock;
    }

    public void fix() {
        setVisibility(View.GONE);
    }

    public void fixLandspace() {
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT < 16) {
                    getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                requestLayout();
            }
        });
    }

    // 为了在进度条消失的时候 AB循环开启的时候，没有执行AB的循环，所以这里在后台需要刷新进度来保证AB循环的逻辑继续运行。
    Handler timingHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (isAbShow && !isShowing()) {
                refreshProgress();
                sendEmptyMessageDelayed(0,1000);
            }
        }
    };

    public void clearABPosition(){
        mProgress.clearABPosition();
    }

}
